<template>
  <div class="setting-model-details-view" style="min-height: calc(100vh - 50px)">

    <modules-title class="title-position" :titleName="title">

      <template slot="btn">
        <el-button plain  size="mini" @click="goBack">返回</el-button>

        <el-button type="primary"  size="mini" @click="saveClick">保存</el-button>

        <el-button type="primary"  size="mini" @click="saveAndUpdate">保存并启用</el-button>
      </template>

    </modules-title>


    <div class="pj-content">
      <div class="content-view">


        <!--      <el-tabs v-model="activeName" @tab-click="handleClick">-->
        <!--        <el-tab-pane label="基本信息" name="first">-->

        <!--          <div class="infomation-view">-->
        <!--            <el-form :model="form" class="demo-form-inline" label-width="100px" label-position="left">-->
        <!--              <el-form-item label="项目模版名称">-->
        <!--                <el-input v-model="form.project_template_name"></el-input>-->
        <!--              </el-form-item>-->
        <!--              <el-form-item label="适用项目阶段">-->
        <!--                <el-select v-model="form.project_phases_name" placeholder="请选择" @change="stageChange">-->
        <!--                  <el-option-->
        <!--                    v-for="item in options"-->
        <!--                    :key="item.label"-->
        <!--                    :label="item.label"-->
        <!--                    :value="item">-->
        <!--                  </el-option>-->
        <!--                </el-select>-->
        <!--              </el-form-item>-->
        <!--              <el-form-item label="适用注册类别">-->
        <!--                <el-select v-model="form.project_category_name" placeholder="请选择" @change="categoryChange">-->
        <!--                  <el-option-->
        <!--                    v-for="item in options2"-->
        <!--                    :key="item.label"-->
        <!--                    :label="item.label"-->
        <!--                    :value="item">-->
        <!--                  </el-option>-->
        <!--                </el-select>-->
        <!--              </el-form-item>-->

        <!--            </el-form>-->
        <!--          </div>-->


        <!--        </el-tab-pane>-->
        <!--        <el-tab-pane label="配置WBS任务计划" name="second">-->

        <!--          <plan-list ref="planList" :documents="documents" :plans="plans"></plan-list>-->

        <!--        </el-tab-pane>-->
        <!--        <el-tab-pane label="交付物清单" name="third">-->
        <!--          <edit-document-view :documents="documents" :plans="plans" @delectDoc="delectDoc" @addDoc="addDoc"></edit-document-view>-->
        <!--        </el-tab-pane>-->
        <!--      </el-tabs>-->


        <!--      <el-collapse v-model="activeNames" @change="handleChange">-->
        <!--        <el-collapse-item title="基本信息" name="1">-->
        <!--          <div class="infomation-view">-->
        <!--            <el-form :model="form" class="demo-form-inline" label-width="100px" label-position="left">-->
        <!--              <el-form-item label="项目模版名称">-->
        <!--                <el-input v-model="form.project_template_name"></el-input>-->
        <!--              </el-form-item>-->
        <!--              <el-form-item label="适用项目阶段">-->
        <!--                <el-select v-model="form.project_phases_name" placeholder="请选择" @change="stageChange">-->
        <!--                  <el-option-->
        <!--                    v-for="item in options"-->
        <!--                    :key="item.label"-->
        <!--                    :label="item.label"-->
        <!--                    :value="item">-->
        <!--                  </el-option>-->
        <!--                </el-select>-->
        <!--              </el-form-item>-->
        <!--              <el-form-item label="适用注册类别">-->
        <!--                <el-select v-model="form.project_category_name" placeholder="请选择" @change="categoryChange">-->
        <!--                  <el-option-->
        <!--                    v-for="item in options2"-->
        <!--                    :key="item.label"-->
        <!--                    :label="item.label"-->
        <!--                    :value="item">-->
        <!--                  </el-option>-->
        <!--                </el-select>-->
        <!--              </el-form-item>-->

        <!--            </el-form>-->
        <!--          </div>-->
        <!--        </el-collapse-item>-->
        <!--        <el-collapse-item title="配置WBS任务计划" name="2">-->
        <!--          <plan-list ref="planList" :documents="documents" :plans="plans"></plan-list>-->
        <!--        </el-collapse-item>-->
        <!--      </el-collapse>-->

        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>基本信息</span>
          </div>
          <div class="infomation-view">
            <el-form ref="form" :model="form" :inline="true" :rules="rules" class="demo-form-inline" label-width="110px" label-position="left">
              <el-form-item label="项目模板名称" prop="project_template_name">
                <el-input v-model="form.project_template_name" placeholder="请输入项目模板名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="适用项目阶段" prop="project_phases_id">
                <el-select v-model="form.project_phases_id" placeholder="请选择项目阶段" clearable @change="stageChange">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="申报类别" prop="project_category_id">
                <el-select v-model="form.project_category_id" placeholder="请选择申报类别" clearable @change="categoryChange">
                  <el-option
                    v-for="(item,index) in options2"
                    :key="index"
                    :label="item.dict_val"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-form>
          </div>
        </el-card>

        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>配置WBS任务计划</span>
            <el-button type="primary" size="mini" @click="addPlan">添加里程碑</el-button>
          </div>
          <plan-list ref="planList" :documents="documents" :plans="plans" @save-change="automaticSave"></plan-list>
        </el-card>

      </div>
    </div>




  </div>
</template>

<script>
  import planList from './modules/planList'
  import editDocumentView from "./modules/editDocumentView";

  const vue = {
      name: 'Index',
      components: { planList , editDocumentView },
      data: function() {
          var validatePass = (rule, value, callback) => {
              if (value) {
                  let id = this.$route.query.id || ''
                  this.$api.PROJECT_TEMPLATE_EXIST(value,id).then(res=>{
                      if (res.code == 200){
                          if (res.data){
                              callback("模板名称已存在");
                          }else{
                              callback()
                          }
                      }else {
                          this.$message.error(res.msg);
                          callback()
                      }

                  }).catch(err=>{
                      callback();
                      this.$message.error(err);
                  })
              }
          };
          return {
              oldDataStr:'',
              activeName: 'first',
              activeNames:'1',
              form:{
                  project_template_name:'',
                  project_phases_id:'',
                  project_phases_name:'',
                  project_category_id:'',
                  project_category_name:'',
                  project_task:[],
                  value:'',
                  status:1,
              },
              options: [
                  {
                      label: "临床前研究",
                      value: "1",
                  },
                  {
                      label: "临床研究",
                      value: "2",
                  },
              ],
              options2: [],
              documents:{
                  id:1,
                  list:[]
              },
              plans:[],
              title:'模板编辑',

              rules: {
                  project_template_name: [
                      { required: true, message: '请输入项目模板名称', trigger: 'blur' },
                      { validator: validatePass, trigger: 'blur' }
                  ],
                  project_phases_id: [
                      { required: true, message: '请选择适用项目阶段', trigger: 'change' }
                  ],
                  project_category_id: [
                      { required: true, message: '请选择申报类别', trigger: 'change' }
                  ],
              },
          }
      },
      beforeRouteLeave(to,form,next){
          let str = JSON.stringify(this.form)

          if (str == this.oldDataStr){

              next()
          }else {
              this.$confirm('此页面已修改, 是否继续离开?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                  next()
              }).catch(() => {
                  next(false);
              });

          }

      },
      mounted: function() {

          if (this.$route.query.id){
              this.getData(this.$route.query.id);
              this.title = "项目模板编辑"
          }else if (this.$route.query.copy_id) {
              this.getData(this.$route.query.copy_id);
              this.title = "项目模板新增"
          } else {
              this.title = "项目模板新增"
              this.oldDataStr = JSON.stringify(this.form);
          }
          this.getBaseData();
          this.$route.meta.this = this;
      },
      methods: {
          getBaseData:function(){

              if (this.$store.getters.sysDic('register_type')){
                  this.options2 = this.$store.getters.sysDic('apply_type');
              }else {
                  this.$store.dispatch("sys/getSysAllDic").then(data=>{
                      this.options2 = data['apply_type'];
                  })
              }
          },
          handleChange(val) {
              console.log(val);
          },
          getData:function(id){
              this.$api.PROJECT_TEMPLATE_DETAIL(id).then(res=>{
                  if (res.code == 200){
                      this.form = res.data;

                      if (this.$route.query.id){
                          this.form.status = 1;
                      }else if (this.$route.query.copy_id){
                          this.form.id = ""
                          this.form.project_template_name = this.form.project_template_name + "(复制)"
                          this.form.status = 1;
                      }
                      this.oldDataStr = JSON.stringify(this.form);
                      if (this.$refs.planList){
                          this.$refs.planList.setData(this.form.project_task)
                      }
                      this.dealDocument(this.form.project_task);
                  }else {
                      this.$message.error(res.msg)
                  }
              }).catch(err=>{

              })
          },
          dealDocument:function (list) {
              for (let i = 0; i < list.length; i++){
                  this.plans.push(list[i]);
                  if (Number(list[i].id) >= this.$refs.planList.id){
                      this.$refs.planList.id = Number(list[i].id) + 1;
                  }
                  this.documents.list = this.documents.list.concat(list[i].files)
                  if (list[i].children && list[i].children.length){
                      this.dealDocument(list[i].children);
                  }
              }
          },
          stageChange:function(value){
              let index = this.options.findIndex(a=>a.value == value)
              if (index != -1){
                  let data = this.options[index]
                  this.form.project_phases_id = data.value;
                  this.form.project_phases_name = data.label;
              }

          },
          categoryChange:function(value){
              let index = this.options2.findIndex(a=>a.id == value)
              if (index != -1){
                  let data = this.options2[index]
                  this.form.project_category_id = data.id;
                  this.form.project_category_name = data.dict_val;
              }
          },
          goBack:function(){
              this.$router.back()
          },
          handleClick: function() {

          },
          delectDoc:function (doc) {
              if (this.$refs.planList){
                  this.$refs.planList.deleteDoc(doc)
              }
          },
          addDoc:function (doc) {
              if (this.$refs.planList){
                  this.$refs.planList.addDoc(doc)
              }
          },
          addPlan:function(){
              this.activeNames = "2";
              if (this.$refs.planList){
                  this.$refs.planList.addPlan()
              }
          },
          automaticSave:function(){
              let data = JSON.parse(this.oldDataStr)
              if (data.id){
                  data.project_task = this.$refs.planList.tableData;

                  this.$api.PROJECT_TEMPLATE_UPDATE(data).then(res=>{
                      if (res.code == 200){
                          this.oldDataStr = JSON.stringify(data)
                      }
                  }).catch(err=>{

                  })
              }
          },
          saveClick:function () {
              if (!this.$refs.form || !this.$refs.planList){
                  return;
              }

              this.$refs.form.validate((valid)=>{
                  if (valid){
                      this.form.project_task = this.$refs.planList.tableData;

                      if (this.form.id){
                          this.$api.PROJECT_TEMPLATE_UPDATE(this.form).then(res=>{
                              if (res.code == 200){
                                  this.oldDataStr = JSON.stringify(this.form)
                                  this.$router.back();

                              }else {
                                  this.$message.error(res.msg)
                              }
                          }).catch(err=>{

                          })
                      }else{
                          this.$api.PROJECT_TEMPLATE_CREATE(this.form).then((res)=>{
                              if (res.code == 200){
                                  this.oldDataStr = JSON.stringify(this.form)
                                  this.$router.back();
                              }else {
                                  this.$message.error(res.msg)
                              }
                          }).catch((err)=>{

                          })
                      }
                  }
              })

          },
          saveAndUpdate:function () {
              if (!this.$refs.form || !this.$refs.planList){
                  return;
              }

              this.$refs.form.validate((valid)=>{
                  if (valid){

                      if (this.form.id){
                          this.form.project_task = this.$refs.planList.tableData;

                          this.$api.PROJECT_TEMPLATE_UPDATE(this.form).then(res=>{
                              if (res.code == 200){
                                  this.oldDataStr = JSON.stringify(this.form)
                                  this.updateModel();

                              }else {
                                  this.$message.error(res.msg)
                              }
                          }).catch(err=>{

                          })
                      }else{
                          this.$api.PROJECT_TEMPLATE_CREATE(this.form).then((res)=>{
                              if (res.code == 200){
                                  this.form.id = res.data;
                                  this.oldDataStr = JSON.stringify(this.form)
                                  this.updateModel();
                              }else {
                                  this.$message.error(res.msg)
                              }
                          }).catch((err)=>{

                          })
                      }


                  }
              })
          },
          updateModel:function () {
              if (!this.form.project_task.length){
                  this.$message.error("请添加里程碑")
                  return;
              }
              this.$api.PROJECT_TEMPLATE_STATUS(this.form.id).then(res=>{
                  if (res.code == 200){
                      this.$message.success('保存并启用成功')
                      this.$router.back();
                  }else {
                      this.$message.error(res.msg)
                  }
              }).catch(err=>{

              })
          }
      }
  }
  export default vue

</script>

<style lang="scss">
  @import "../../../../assets/scss/views/setting/model/edit.scss";
</style>
